from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired,BadSignature
from mall import settings


def generate_openid_token(openid):
    # 创建序列化器
    s = Serializer(settings.SECRET_KEY, expires_in=60*10)
    # 组织数据
    data = {
        'openid': openid
    }
    # 加密
    token = s.dumps(data)
    # 返回字符串
    return token.decode()


def check_access_token(token):
    # 创建序列化器
    s = Serializer(settings.SECRET_KEY,expires_in=60*10)
    # 解密,可能解密失败，要捕获异常
    try:
        result = s.loads(token)
    except BadSignature:
        return None
    # 返回数据
    return result.get('openid')



